import { setState } from './index'
import { query, mutation } from '../utils/http'

function apiGetInfo() {
  return new Promise((resolve, reject) => {
    wx.getUserInfo({
      success: res => resolve(res),
      fail: err => reject(err)
    })
  })
}

function apiSaveUserInfo(token, { encryptedData, iv }) {
  const str = `
    mutation ($info:AuthWechatUserRequest){
      authWechatUser(request:$info)
    }
  `
  return mutation(token, str, { info: { encryptedData, iv } })
}

function apiGetUserDetail(token) {
  const str = `
    {
      wechatUserInfo{
        name
        mobile
        email
        identityType
        identityNumber
        gender
        nickname
        headImgUrl
        country
        province
        city
        countryCode
        language
      }
    }
  `
  return query(token, str)
}

function apiGetUserTraveler(token) {
  const str = `
  {
    userTravelers{
      id
      createTime
      updateTime
      name
      countryCode
      mobile
      identityType
      identityNumber
      email
      status
    }
  }
  `
  return query(token, str)
}

function apiAddUserTraveler(
  token,
  { id, name, countryCode, mobile, identityType, identityNumber, email }
) {
  const str = `
    ($input:UserTravelerInput!){
    addUserTraveler(input: $input){
      id
      createTime
      updateTime
      name
      countryCode
      mobile
      identityType
      identityNumber
      email
      status
    }
  }`
  return mutation(token, str, {
    input: { id, name, countryCode, mobile, identityType, identityNumber, email }
  })
}

function apiGetSmsCode(mobile) {
  const str = `
  ($mobile:String!){
    sendSmsCode(mobile:$mobile)
  }
  `
  return mutation({}, str, { mobile }, { url: 'https://api.hilval.com/hilval-common-web/graphql' })
}

function apiCheckSmsCode(params) {
  const str = `
    ($params:CheckSmsCodeInput!){
      checkSmsCode(request: $params)
    }
  `
  return query(
    {},
    str,
    { params: params },
    { url: 'https://api.hilval.com/hilval-common-web/graphql' }
  )
}

const state = {
  isLogin: false,
  userInfo: {},
  travelers: [],

  smsToken: ''
}

const mutations = { setState }

const actions = {
  // 授权登陆

  async getUserInfo({ rootState, commit, dispatch }, params) {
    const token = rootState.Client.token
    try {
      const { encryptedData, iv, userInfo } = params || (await apiGetInfo())
      // 存入后台
      await apiSaveUserInfo(token, { encryptedData, iv })
      commit('setState', {
        isLogin: true,
        userInfo
      })
      console.log('授权成功 ===>', rootState.User)
      dispatch('getTravelers')
    } catch (err) {
      console.error('用户未授权', err)
    }
  },

  async getTravelers({ rootState, commit }) {
    const token = rootState.Client.token
    try {
      const res = await apiGetUserTraveler(token)
      if (res.data.data && res.data.data.userTravelers) {
        commit('setState', { travelers: res.data.data.userTravelers })
      }
    } catch (err) {
      console.error(err)
    }
  },

  addTraveler(
    { rootState, dispatch },
    { name, countryCode = '86', mobile, identityType, identityNumber, email = '' }
  ) {
    const token = rootState.Client.token
    return new Promise((resolve, reject) => {
      apiAddUserTraveler(token, {
        name,
        countryCode,
        mobile,
        identityType,
        identityNumber,
        email
      })
        .then(res => {
          if (res.data.data && res.data.data.addUserTraveler) {
            dispatch('getTravelers')
            resolve()
          } else {
            reject()
          }
        })
        .catch(err => reject(err))
    })
  },

  async updateTraveler(
    { rootState, dispatch },
    { id, name, countryCode = '86', mobile, identityType, identityNumber, email = '' }
  ) {
    const token = rootState.Client.token
    const str = `
      ($input:UserTravelerInput!){
      updateUserTraveler(input:$input)
    }`
    try {
      const res = await mutation(token, str, {
        input: { id, name, countryCode, mobile, identityType, identityNumber, email }
      })
      if (res.data.data && res.data.data.updateUserTraveler) {
        dispatch('getTravelers')
      }
    } catch (err) {
      console.error(err)
    }
  },

  deleteTraveler({ rootState, commit, dispatch }, id) {
    const token = rootState.Client.token
    const str = `
    ($id:Long!){
      deleteUserTraveler(id:$id)
    }`
    return new Promise((resolve, reject) => {
      mutation(token, str, { id }).then(res => {
        if (res.data.data && res.data.data.deleteUserTraveler) {
          dispatch('getTravelers')
          resolve()
        } else {
          reject()
        }
      })
    })
  },

  async getSms({ commit }, mobile) {
    try {
      const sms = await apiGetSmsCode(mobile)
      console.log(sms)
      commit('setState', { smsToken: sms.data.data.sendSmsCode })
    } catch (err) {
      console.error(err)
    }
  },

  async checkSignUp({ state }, { mobile, smsCode }) {
    try {
      const isSignUp = await apiCheckSmsCode({ mobile, smsCode, smsToken: state.smsToken })
      console.log(isSignUp)
    } catch (err) {
      console.error(err)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
